package com.wangwei.modules.container


import com.wangwei.modules.filter.Filter
import com.wangwei.modules.filter.SpFilter
import com.wangwei.modules.servlet.DispatcherServlet
import com.wangwei.modules.servlet.MyServlet
import com.wangwei.modules.utils.FileUtil
import com.wangwei.modules.utils.HttpResponseUtil.ContentType
import org.springframework.ui.RedirectAttributesModelMap
import java.io.PrintWriter
import java.io.StringWriter
import java.net.ServerSocket
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


/**
启动监听
 */
fun main(args: Array<String>) {
	WebContainer().start()
}

/**
 *web容器
 */
class WebContainer {

	companion object {
		var CLASS_PATH = javaClass.getClassLoader().getResource("").getPath()
		var WEB_ROOT_PATH = CLASS_PATH.substring(0, CLASS_PATH.length - 1 - 4 - 11) + "/webapps"
	}


	fun start() {
		//加入普通的servlet
		ServletFactory.addWebServlet("/cc", MyServlet::class.java.getName());
		//加入spring servlet
		ServletFactory.addWebServlet("/.*", DispatcherServlet::class.java.getName());

		//启动
		var serverSocket: ServerSocket = ServerSocket(666)

		System.out.println("Server is starting " + serverSocket)

		while (true) {
			try {
				var socket = serverSocket.accept()

				Thread(Runnable {
					kotlin.run {
						var responce: HttpServletResponse = HttpServletResponse(socket.getOutputStream())
						var request: HttpServletRequest = HttpServletRequest(socket.getInputStream())
						dealConfigs(request, responce)
					}
				}).start()

			} catch (e: Exception) {
				e.printStackTrace()
			}
		}
	}



	/**
	 * 处理页面响应
	 *
	 * @param configs
	 * @throws IOException
	 */
	fun dealConfigs(request: HttpServletRequest, responce: HttpServletResponse) {
		if ("".equals(request.url)) {
			//TODO 现在是不操作，以后是进主页
			return
		}
		println(request.url)
        /*
         * 进入过滤器
         */
		var filters = arrayListOf<Filter>(SpFilter())

		for (filter in filters) {
			try {
				var bool = filter.doFilter(request, responce)
				if (!bool) return
			} catch (e: Exception) {
				return
			}
		}

		//不进servlet的资源
		if (request.getSuffix() == null) {
			println(request.getSuffix())
			try {
				//servlet
				var servlet = ServletFactory.getNormalMethodByPath(request.url);
				if (servlet != null) {
					servlet.service(request, responce)
					return
				}
			} catch (e: Exception) {//400
					responce.location("/400.html", RedirectAttributesModelMap().addAttribute("error",getTrace(e)))
			}
		}


		//进页面web
		if (request.url != null) {
			var filepath = WEB_ROOT_PATH + request.url
			try {
				var file = FileUtil.getBytes(filepath)
				responce.output(file, ContentType.getByName(filepath))
			} catch (e: Exception) {//404
				responce.location("/400.html",null)
			}
		}
	}
	
		/**
	 * 异常日志扑捉打印
	 */
	fun  getTrace( t:Throwable) :String{
		var stringWriter =  StringWriter();
		var writer =  PrintWriter(stringWriter);
		t.printStackTrace(writer);
		var buffer = stringWriter.getBuffer();
		return buffer.toString();
	}
}
